<template>
  <div class="app-main-container">
    <!-- <div class="app-main-title">{{ $t('message.ddlb') }}</div> -->
    <QueryForm
      v-model="filters"
      :query-form-config="queryFormConfig"
      @handleQuery="getList(1)"
      @clear="clear"
    >
      <template #btns>
        <el-button
          v-if="meta.indexOf('MealsPcOrderListExport') > -1"
          :loading="exportLoading"
          type="primary"
          @click="comboOrderExport"
          >{{ $t("message.daochu") }}</el-button
        >
      </template>
    </QueryForm>
    <el-table
      ref="table"
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      :header-row-class-name="'table-header'"
      class="doumee-element-tableb"
    >
      <el-table-column
        align="center"
        :label="$t('message.ddbh')"
        min-width="210"
        show-overflow-tooltip
      >
        <template v-slot="scope">
          <span class="ckxqBtn" @click="handleDetail(scope.row.orderId)">{{
            scope.row.orderId
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        :label="$t('message.tcnr')"
        prop="name"
        min-width="300"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          <span v-for="(item, index) in scope.row.orderInfo" :key="index">{{
            mealData(item)
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        :label="$t('message.heji')"
        prop="allPrice"
        min-width="100"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        :label="$t('message.hyzkj')"
        prop="realPrice"
        min-width="100"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        :label="$t('message.ddly')"
        min-width="100"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.channelTypeName }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        :label="$t('message.zffs')"
        min-width="120"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.payMethodName }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('message.memberInfo')"
        min-width="260"
        align="center"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          <span class="name">{{ scope.row.memberName }}</span>
          <span v-if="scope.row.memberPhone" class="phone"
            >-{{ scope.row.memberPhone }}</span
          >
          <span v-if="scope.row.memberCardId" class="phone"
            >-{{ scope.row.memberCardId }}</span
          >
        </template>
      </el-table-column>
      <!-- <el-table-column align="center" :label="$t('message.hykh')" prop="memberCardId" min-width="100" show-overflow-tooltip /> -->
      <el-table-column
        align="center"
        :label="$t('message.bz')"
        prop="remarks"
        min-width="200"
        show-overflow-tooltip
      />
      <el-table-column
        :label="$t('message.czy')"
        prop="creator"
        min-width="120"
        align="center"
        show-overflow-tooltip
      />
      <el-table-column
        :label="$t('message.createTime')"
        prop="createTime"
        min-width="160"
        align="center"
      />
      <el-table-column
        :label="$t('message.ddzt')"
        prop="createTime"
        fixed="right"
        min-width="100"
        align="center"
        show-overflow-tooltip
      >
        <!-- status -->
        <template slot-scope="scope">
          <span
            v-if="scope.row.status == '0'"
            class="primaryColor pointer"
            @click="getOrderType(scope.row.orderId)"
            >{{ scope.row.statusName }}</span
          >
          <span v-else>{{ scope.row.statusName }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('message.caozuo')"
        :width="$i18n.locale === 'ZH' ? 180 : 350"
        align="center"
        fixed="right"
      >
        <template slot-scope="scope">
          <div class="flex-cc">
            <div v-if="scope.row.status == '0'">
              <el-button
                v-if="meta.indexOf('ComboOrderPayContinue') > -1"
                v-preventReClick
                type="text"
                @click="payContinue(scope.row)"
                >{{ $t("message.jxzf") }}</el-button
              >
              <el-button
                v-if="meta.indexOf('ComboOrderPayCancel') > -1"
                v-preventReClick
                type="text"
                @click="cancleBuy(scope.row.orderId)"
                >{{ $t("message.qxgm") }}</el-button
              >
            </div>
            <div v-else-if="scope.row.status == '3'">
              <el-button
                v-if="meta.indexOf('ComboOrderCancel') > -1"
                v-preventReClick
                type="text"
                @click="mealRefund(scope.row.orderId)"
                >{{ $t("message.tctk") }}</el-button
              >
              <el-button
                v-if="meta.indexOf('ComboPrinterOrder') > -1"
                v-preventReClick
                type="text"
                @click="printTic(scope.row.orderId)"
                >{{ $t("message.dyxp") }}</el-button
              >
            </div>
            <div v-else>-</div>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <Paginations
      :total="total"
      :page="pagination.page"
      @current-change="getList"
      @SizeChange="handleSizeChange"
    />
    <orderDialog ref="child" @orderSuccess="getList()" />
    <ComboDetail ref="ComboDetailRef" />
    <ComboTem v-if="isPrint" ref="ComboTemRef" />
    <PrintTable
      ref="PrintTableRef"
      @cancelDialog="cancelDialog"
      @printd="printd"
    />
  </div>
</template>

<script>
import {
  getChannelType,
  mealOrderList,
  mealCancel,
  mealRefund,
  getOrderTypeQuery,
  printOrder,
  orderType,
  allConfigList,
  mealOrderExport,
} from "@/api";
import { parseTime, parseTimeb } from "@/utils";
import QueryForm from "@/components/QueryForm";
import orderDialog from "@/components/order";
import ComboDetail from "./detail.vue";
import { TJshortcuts } from "@/utils/config";
import ComboTem from "@/components/printTem/combo.vue";
import PrintTable from "@/components/printTable.vue";
export default {
  name: "ComboOrderList",
  components: {
    orderDialog,
    PrintTable,
    QueryForm,
    ComboDetail,
    ComboTem,
  },
  data() {
    return {
      exportLoading: false,
      isPrint: false,
      printList: [],
      queryFormConfig: {
        formItems: [
          {
            filed: "orderId",
            type: "input",
            label: this.$t("message.ddbh"),
            clearable: true,
          },
          {
            filed: "mealsName",
            type: "input",
            label: this.$t("message.tcname"),
            clearable: true,
          },
          {
            filed: "time",
            type: "daterange",
            clearable: true,
            label: this.$t("message.cjrq"),
            pickerOptions: {
              shortcuts: TJshortcuts,
            },
          },
          {
            filed: "channelType",
            type: "select",
            label: this.$t("message.ddly"),
            clearable: true,
            options: [],
          },
          {
            filed: "payMethod",
            type: "select",
            label: this.$t("message.zflx"),
            clearable: true,
            options: [],
          },
          {
            filed: "payStatus",
            type: "select",
            label: this.$t("message.ddzt"),
            placeholder: this.$t("message.qxz") + this.$t("message.ddzt"),
            clearable: true,
            labelCode: "name",
            options: [
              { value: "0", name: this.$t("message.dzf") },
              { value: "1", name: this.$t("message.cswzf") },
              { value: "2", name: this.$t("message.qxzf") },
              { value: "3", name: this.$t("message.zfcg") },
              { value: "4", name: this.$t("message.tkz") },
              { value: "5", name: this.$t("message.tkcg") },
            ],
          },

          {
            filed: "memberInfo",
            type: "input",
            label: this.$t("message.memberInfo"),
            placeholder: this.$t("message.hy2"),
            clearable: true,
          },
        ],
        online: true,
      },
      meta: [],
      list: [],
      pagination: {
        page: 1,
        rows: 10,
      },
      total: 0,
      payTypes: [],
      listLoading: false,
      filters: {
        time: [parseTimeb(7).slice(0, 10), parseTime(new Date()).slice(0, 10)],
      },
    };
  },
  created() {
    this.meta = this.$route.meta.buttons || [];
    this.initData();
    this.getChannel();
    this.getOrderStatusList();
    this.getList(1);
  },
  mounted() {
    this.$nextTick(() => {
      this.$refs.table.doLayout();
    });
  },
  activated() {
    this.$nextTick(() => {
      this.$refs.table.doLayout();
      this.getList(1);
    });
  },
  methods: {
    printTic(id) {
      // 打印小票
      const venueId = sessionStorage.getItem("venueId");
      this.isPrint = true;
      if (window.Android) {
        Android.print("MEALSTPML", id, "");
        return;
      }
      printOrder({ param: { venueId, templateCode: "MEALSTPML", workId: id } })
        .then((res) => {
          if (res.errorCode === "000000") {
            if (
              res.record &&
              res.record.isPrint === "1" &&
              res.record.dataList &&
              res.record.dataList.length > 0
            ) {
              this.printList = res.record.dataList;
              if (res.record.dataList.length === 1) {
                res.record.dataList.forEach((item) => {
                  this.$refs.ComboTemRef.obj = { ...item };
                  setTimeout(() => {
                    this.$refs.ComboTemRef.print();
                  }, 300);
                  setTimeout(() => {
                    this.isPrint = false;
                  }, 500);
                });
              } else {
                this.isPrint = false;
                this.$refs.PrintTableRef.showDetail(res.record);
              }
            } else {
              this.isPrint = false;
            }
          } else {
            this.isPrint = false;
          }
        })
        .catch((err) => {
          this.isPrint = false;
          console.log(err);
        });
    },
    printd(index) {
      this.isPrint = true;
      const arr = [...this.printList];
      setTimeout(() => {
        this.$refs.ComboTemRef.obj = { ...arr[index] };
      }, 300);
      setTimeout(() => {
        this.$refs.ComboTemRef.print();
      }, 500);
      setTimeout(() => {
        this.isPrint = false;
      }, 1000);
    },
    cancelDialog() {
      this.isPrint = false;
    },
    getChannel() {
      getChannelType({ param: { code: "CHANNEL_MEALS" } }).then((res) => {
        this.queryFormConfig.formItems[3].options = res.recordList.map(
          (item) => {
            return {
              label: item.name,
              value: item.value,
            };
          }
        );
      });
    },
    getOrderStatusList() {
      getOrderTypeQuery({ param: {} }).then((res) => {
        this.queryFormConfig.formItems[5].options = res.recordList || [];
      });
    },
    handleSizeChange(value) {
      this.pagination.rows = value;
      this.getList(1);
    },
    handleDetail(orderId) {
      this.$refs.ComboDetailRef.getOrderDetail(orderId);
    },
    comboOrderExport() {
      const { filters } = this;
      if (filters.time && filters.time.length > 0) {
        filters.startDate = filters.time[0] + " 00:00:00";
        filters.endDate = filters.time[1] + " 23:59:59";
      } else {
        filters.startDate = null;
        filters.endDate = null;
      }
      this.exportLoading = true;
      mealOrderExport({
        param: {
          ...filters,
          venueId: sessionStorage.getItem("venueId"),
        },
      })
        .then((res) => {
          this.exportLoading = false;
          if (res.errorCode === "000000") {
            if (window.Android) {
              Android.downloadFile(res.record.showUrl);
              return;
            }
            const a = document.createElement("a"); // 创建一个a标签元素
            a.style.display = "none"; // 设置元素不可见
            a.href = res.record.showUrl; // 设置下载地址
            document.body.appendChild(a); // 加入
            a.click(); // 触发点击,下载
            document.body.removeChild(a); //
            this.$message.success(this.$t("message.dccg"));
          }
        })
        .catch(() => {
          this.exportLoading = false;
        });
    },
    getOrderType(orderId) {
      orderType({
        param: {
          orderId,
        },
      })
        .then((res) => {
          const str = res.record.msg;
          if (res.errorCode === "000000") {
            if (res.record.code === "0") {
              this.$message.success(str);
              this.getList();
            } else if (res.record.code === "2") {
              this.$message.info(str);
            } else {
              this.$message.error(str);
              this.getList();
            }
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    mealData(meal) {
      if (meal.validityType === "1") {
        return (
          meal.name +
          (meal.type !== "1"
            ? "   " +
              this.$t("message.cs") +
              "：" +
              meal.num +
              this.$t("message.ci")
            : "") +
          (meal.type === "2" || meal.type === "0"
            ? "   " +
              this.$t("message.zscs") +
              "：" +
              meal.giveNums +
              this.$t("message.ci")
            : "") +
          "   " +
          this.$t("message.num") +
          "：" +
          meal.mealsNum +
          "   " +
          this.$t("message.yxq") +
          "：" +
          meal.indate +
          this.$t("message.tian") +
          "   " +
          this.$t("message.oldprice") +
          "：" +
          meal.price
        );
      }
      if (meal.validityType === "2") {
        return (
          meal.name +
          (meal.type !== "1"
            ? "   " +
              this.$t("message.cs") +
              "：" +
              meal.num +
              this.$t("message.ci")
            : "") +
          (meal.type === "2" || meal.type === "0"
            ? "   " +
              this.$t("message.zscs") +
              "：" +
              meal.giveNums +
              this.$t("message.ci")
            : "") +
          "   " +
          this.$t("message.num") +
          "：" +
          meal.mealsNum +
          "   " +
          this.$t("message.yxq") +
          "：" +
          meal.validityStartTime +
          " - " +
          meal.validityEndTime +
          "   " +
          this.$t("message.oldprice") +
          "：" +
          meal.price
        );
      } else {
        return (
          meal.name +
          (meal.type !== "1"
            ? "   " +
              this.$t("message.cs") +
              "：" +
              meal.num +
              this.$t("message.ci")
            : "") +
          (meal.type === "2" || meal.type === "0"
            ? "   " +
              this.$t("message.zscs") +
              "：" +
              meal.giveNums +
              this.$t("message.ci")
            : "") +
          "   " +
          this.$t("message.num") +
          "：" +
          meal.mealsNum +
          "   " +
          this.$t("message.gdrq") +
          "：" +
          meal.validityStartTime +
          " - " +
          meal.validityEndTime +
          "   " +
          this.$t("message.oldprice") +
          "：" +
          meal.price
        );
      }
    },
    rStatus(status) {
      switch (status) {
        case "0":
          return this.$t("message.dzf");
        case "1":
          return this.$t("message.cswzf");
        case "2":
          return this.$t("message.qxzf");
        case "3":
          return this.$t("message.zfcg");
        case "4":
          return this.$t("message.tkz");
        case "5":
          return this.$t("message.tkcg");
        default:
          return "";
      }
    },
    nameWithPayMethod(payM) {
      const payType = this.payTypes.find((item) => item.value === payM);
      return payType ? payType.name : "-";
    },
    initData() {
      allConfigList({ param: { type: "2", code: "1" } })
        .then((res) => {
          if (res.errorCode === "000000") {
            const arrb = res.recordList;
            arrb.forEach((e) => {
              e.label = e.name;
            });
            this.queryFormConfig.formItems[4].options = arrb;
            this.payTypes = res.recordList;
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    getList(page) {
      const { filters, pagination } = this;
      if (page) {
        pagination.page = page;
        this.pagination.page = Number(page);
      }
      pagination.firstQueryTime = parseTime(new Date());
      if (filters.time && filters.time.length > 0) {
        filters.startDate = filters.time[0] + " 00:00:00";
        filters.endDate = filters.time[1] + " 23:59:59";
      } else {
        filters.startDate = null;
        filters.endDate = null;
      }
      this.listLoading = true;
      mealOrderList({
        pagination,
        param: {
          ...filters,
          venueId: sessionStorage.getItem("venueId"),
        },
      })
        .then((res) => {
          this.listLoading = false;
          if (res.errorCode === "000000") {
            this.list = res.recordList;
            this.total = res.totalCount;
            if (
              res.totalCount &&
              res.recordList.length === 0 &&
              pagination.page > 1
            ) {
              this.getList(Math.ceil(res.totalCount / pagination.rows));
            }
          }
        })
        .catch(() => {
          this.listLoading = false;
        });
    },
    clear() {
      this.filters = { time: [] };
      this.getList(1);
    },
    payContinue(row) {
      this.$refs.child.continuePay(row, "comboOrder");
    },
    cancleBuy(id) {
      // 取消购买
      this.$alert(this.$t("message.qxgmtctc"), this.$t("message.jingao"), {
        confirmButtonText: this.$t("message.qd"),
        callback: (action) => {
          if (action === "confirm") {
            mealCancel({ param: { id } }).then((res) => {
              if (res.errorCode === "000000") {
                this.getList();
              }
            });
          }
        },
      });
    },
    mealRefund(id) {
      // 退款
      this.$alert(this.$t("message.tctktc"), this.$t("message.jingao"), {
        confirmButtonText: this.$t("message.qd"),
        callback: (action) => {
          if (action === "confirm") {
            mealRefund({ param: { id } }).then((res) => {
              if (res.errorCode === "000000") {
                this.getList();
              }
            });
          }
        },
      });
    },
  },
};
</script>

<style lang='scss' scoped>
.division-line {
  text-align: center;
  display: inline-block;
  color: #999;
  width: 30px;
}

.bottom-style {
  height: 50px;
  border-left: 1px #dfe2e8 solid;
  border-right: 1px #dfe2e8 solid;
  border-bottom: 1px #dfe2e8 solid;
  .sum-style {
    margin-left: 10px;
    margin-top: 17px;
    height: 15px;
    float: left;
    .sum-title {
      color: #222;
      font-size: 13px;
    }
    .sum-value {
      color: #dd0707;
      font-size: 17px;
      font-weight: 700;
    }
  }
  .btn-style {
    float: right;
    width: 80px;
    height: 30px;
    margin-right: 10px;
    margin-top: 10px;
    background-color: #1943a9;
    color: #fff;
    text-align: center;
    border-radius: 4px;
    line-height: 30px;
    font-size: 13px;
    font-weight: 700;
  }
}
.ticket-style {
  display: inline-block;
  width: 20px;
  height: 20px;
  border: #999 solid 1px;
  border-radius: 10px;
  text-align: center;
  p {
    vertical-align: middle;
    font-weight: 700;
    font-size: 18px;
    line-height: 20px;
    color: #999;
    margin: 0;
  }
}

.count-style {
  margin-left: 5px;
  margin-right: 5px;
}
.pay-style {
  min-width: 80px;
  padding-left: 5px;
  padding-right: 5px;
  height: 30px;
  font-size: 15px;
  line-height: 1px;
  vertical-align: middle;
}
.slelect-pay-style {
  background-color: #1943a9;
  color: #fff;
}
.normal-pay-style {
  border: 1px solid #d8d8d8;
  background-color: #fff;
  color: #222;
}
.messgae-style {
  color: #dd0707;
}
.price-style {
  font-size: 17px;
  font-weight: 500;
}
.unit-style {
  margin-right: 20px;
}
.bottom-speace-style {
  margin-bottom: 10px;
}
.card-message {
  // width: 80%;
  margin-bottom: 10px;
  background-color: #f2f2f2;
  height: 60px;
  line-height: 20px;
  .first-line {
    height: 30px;
    overflow: hidden;
    padding: 5px;
    .message-title-style {
      color: #999;
    }
    .card-name-style {
      display: inline-block;
      border: 1px #999 solid;
      border-radius: 4px;
      background-color: #fff;
      font-size: 12px;
      padding-left: 5px;
      padding-right: 5px;
      height: 20px;
      text-align: center;
    }
    .close-style {
      font-size: 20px;
      float: right;
      margin-right: 5px;
      margin-top: -2px;
      padding: 0;
      border: 0px #999 solid;
    }
    .message-value-style {
      margin-right: 15px;
      color: #222;
    }
  }
}
.footer-style {
  display: flex;
  justify-content: space-between;
  background-color: #f2f2f2;
  margin: -10px -20px -30px;
  height: 50px;
  .bottom-left {
    margin-left: 20px;
    height: 20px;
    margin-top: 15px;
    .sum-title-style {
      font-size: 15px;
      color: #222;
    }
    .sum-pay-value-style {
      font-size: 17px;
      font-weight: 500;
      color: #dd0707;
    }
    .dis-title-style {
      font-size: 14px;
      color: #222;
    }
    .discoun-style {
      font-size: 16px;
      color: #dd0707;
    }
  }
  .bottom-right {
    margin-right: 20px;
    margin-top: 10px;
    height: 30px;
    .pay-action-style {
      width: 100px;
      height: 30px;
      font-size: 15px;
      line-height: 1px;
      vertical-align: middle;
    }
  }
}
</style>
